package com.org.zp.ctrl.myzhaopin;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.org.base.ctrl.BaseActivity;
import com.org.base.util.HttpUtils;
import com.org.base.widget.AutoScrollTextView;
import com.org.base.widget.PageControlView;
import com.org.base.widget.TitleProvider;
import com.org.zp.R;
import com.org.zp.app.RecApp;
import com.org.zp.entity.login.Resume;
import com.org.zp.entity.login.UserInfo;

public class ResumeMgr {
	private static final String TAG = ResumeMgr.class.getCanonicalName();

	private static final int SET_DEF_SUCCESS = 0;// 设置默认简历操作成功
	private static final int SET_DEF_FAILURE = 1;// 设置默认简历操作失败
	private static final int REFRESH_BACK = 2;// 刷新返回
	private static final int NETWORK_UNUSABLE = 12;// 网络不可用

	private ResumeMgrListener resumeMgrListener;
	private RecApp mApp;
	private BaseActivity mActivity;
	private ArrayList<View> mListViews;
	private ResumePagerAdapter resumePagerAdapter;
	private ViewPager pager;
	private PageControlView pageControl;
	private AutoScrollTextView pageTitle;
	private UserInfo userInfo;

	// private PopupWindow mPopupWindow;// 设置默认简历确认窗口
	private LayoutInflater mLayoutInflater;

	private List<Resume> resumes;
	private Resume resume;// 选中的默认简历

	private ProgressDialog progressDialog;

	public ResumeMgr(BaseActivity activity) {
		mActivity = activity;
		mApp = (RecApp) mActivity.getApplication();
		userInfo = mApp.user;
		mLayoutInflater = activity.getLayoutInflater();
	}

	public void show() {
		resumes = mApp.user.getResume();
		if (null == resumes) {
			resumes = new ArrayList<Resume>();
		}
		init();
	}

	private void init() {
		pager = (ViewPager) mActivity.findViewById(R.id.page_body);

		mListViews = new ArrayList<View>();
		generateResume();
		resumePagerAdapter = new ResumePagerAdapter();
		pager.setAdapter(resumePagerAdapter);

		pageTitle = (AutoScrollTextView) mActivity
				.findViewById(R.id.page_title);
		pageControl = (PageControlView) mActivity
				.findViewById(R.id.page_indicator);
		pageControl.setPageTitle(pageTitle);
		pageControl.setViewPager(pager);
		pager.setCurrentItem(0);

		if (null != resumeMgrListener) {
			resumeMgrListener.onComplete();
		}
	}

	private void generateResume() {
		mListViews.clear();
		LayoutInflater inflater = mActivity.getLayoutInflater();
		View view = null;
		int len = resumes.size();
		for (int i = 0; i < len; i++) {
			view = inflater.inflate(R.layout.zp_home_resume_item, null);

			RelativeLayout browseCount_layout = (RelativeLayout) view
					.findViewById(R.id.browseCount_layout);
			browseCount_layout.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					
//					Intent intent = new Intent(mActivity,
//							ResumeReadActivity.class);
//					mActivity.startActivity(intent);
				}
			});

			// 浏览次数
			TextView browseCount = (TextView) view
					.findViewById(R.id.browseCount);
			browseCount.setText("" + resumes.get(i).getShow_count());

			// 刷新
			RelativeLayout refresh_layout = (RelativeLayout) view
					.findViewById(R.id.refresh_layout);
			refresh_layout.setTag(i);
			refresh_layout.setOnClickListener(onClickListener);

			// 设置默认简历
			ImageView defaultResume = (ImageView) view
					.findViewById(R.id.setDefaultResume);
			defaultResume.setTag(i);
			defaultResume.setOnClickListener(onClickListener);
			if ("1".equals(resumes.get(i).getIsdefaultflag())) {
				defaultResume
						.setBackgroundResource(R.drawable.notselected_press);
			} else {
				defaultResume.setBackgroundResource(R.drawable.notselected);
			}
			mListViews.add(view);
		}
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.refresh_layout:// 刷新
				break;
			case R.id.setDefaultResume:// 设置默认简历确认
				resume = resumes.get((Integer) v.getTag());
				confirm(resume);
				break;
			case R.id.cancel:// 设置默认简历-->取消
				// mPopupWindow.dismiss();
				break;
			case R.id.confirm:// 设置默认简历-->确定
				// mPopupWindow.dismiss();
				setDefaultResume(resume);
				break;
			}
		}
	};

	public void confirm(Resume resume) {
		System.out.println(TAG + "-->confirm()");
		/*
		 * if ("1".equals(resume.getIsdefaultflag())) { Toast toast =
		 * Toast.makeText(mActivity, "已经是默认简历", Toast.LENGTH_SHORT);
		 * toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); return; } View
		 * setDefaultResume = mLayoutInflater.inflate(
		 * R.layout.set_default_resume, null); if (null == mPopupWindow) {
		 * mPopupWindow = new PopupWindow(setDefaultResume,
		 * LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true); } if
		 * (mPopupWindow.isShowing()) { mPopupWindow.dismiss(); }
		 * 
		 * Button cancel = (Button) setDefaultResume.findViewById(R.id.cancel);
		 * // 取消 cancel.setOnClickListener(onClickListener);
		 * 
		 * Button confirm = (Button)
		 * setDefaultResume.findViewById(R.id.confirm); // 确定
		 * confirm.setOnClickListener(onClickListener);
		 * 
		 * mPopupWindow.setContentView(setDefaultResume);
		 * mPopupWindow.setAnimationStyle(R.style.PopupAnimation);
		 * mPopupWindow.showAtLocation(mActivity.findViewById(R.id.zphome_root),
		 * Gravity.CENTER, 0, 0); mPopupWindow.update();
		 */

		int messageId;
		if ("1".equals(resume.getIsdefaultflag())) {// 该简历已经为默认简历
			messageId = R.string.set_default_resume_cancel;
		} else {
			boolean existDef = false;
			for (int i = resumes.size() - 1; i >= 0; i--) {
				if ("1".equals(resumes.get(i).getIsdefaultflag())) {
					existDef = true;
					break;
				}
			}
			if (existDef) {// 已存在默认简历
				messageId = R.string.set_default_resume_onlyone;
			} else {// 没有设置默认简历
				// messageId = R.string.set_default_resume_set;
				messageId = R.string.set_default_resume_onlyone;
			}
		}
		AlertDialog.Builder builder = new Builder(mActivity.getParent());
		builder.setMessage(messageId);
		builder.setNegativeButton("取消", clickListener);
		builder.setPositiveButton("确定", clickListener);
		builder.create().show();
	}

	DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.cancel();
			switch (which) {
			case DialogInterface.BUTTON_POSITIVE:
				setDefaultResume(resume);
				break;
			}
		}
	};

	class ResumePagerAdapter extends PagerAdapter implements TitleProvider {

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			// return 0;
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1));
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// return false;
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

		@Override
		public String getTitle(int position) {
			if (resumes.size() < 1) {
				return "";
			}
			return resumes.get(position).getResume_title();
		}

	}

	/**
	 * 设置默认简历
	 * 
	 * @param resume
	 */
	private void setDefaultResume(Resume resume) {
//		progressDialog = ProgressDialog.show(mActivity.getParent(), "",
//				"设置默认简历,请稍后...", true, true);
//		List<RequestParameter> params = new ArrayList<RequestParameter>();
//		params.add(new RequestParameter("resume_id", resume.getResume_id(),
//				false));
//		params.add(new RequestParameter("Resume_number", resume
//				.getResume_number(), false));
//		params.add(new RequestParameter("Version_number", resume
//				.getVersion_number(), false));
//		params.add(new RequestParameter("uticket", mUser.getUticket(), false));
//		if ("1".equals(resume.getIsdefaultflag())) {//已经是默认简历,则取消
//			params.add(new RequestParameter("setflag", "1", false));
//		} else {
//			params.add(new RequestParameter("setflag", "0", false));
//		}
//		// Http Get请求
//		AsyncHttpGet httpget = new AsyncHttpGet(ZhiLianInteface.mJobSetResume
//				+ "?" + Util.getExpandParam(mActivity), params,
//				new RequestCallback() {
//
//					@Override
//					public void onSuccess(Response response) {
//						mActivity.processResponse(mActivity, response,
//								mActivity.getBaseXmlParser(response, null),
//								new DefaultAfterProcessResponseImpl());
//					}
//
//					@Override
//					public void onFail(Exception e) {
//						e.printStackTrace();
//						handler.sendEmptyMessage(SET_DEF_FAILURE);
//					}
//
//				});
//		mActivity.getRequestList().add(httpget);
//		DefaultThreadPool.getInstance().execute(httpget);
	}

//	class DefaultAfterProcessResponseImpl extends DefaultAfterProcessResponse {
//
//		@Override
//		public void afterProcessResponse(BaseHttpActivity activity,
//				Object parseObj) {
//			handler.obtainMessage(SET_DEF_SUCCESS, parseObj).sendToTarget();
//		}
//
//	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (null != progressDialog) {
				progressDialog.dismiss();
			}
			if (msg.what == SET_DEF_SUCCESS) {
//				if ("1".equals(statusEntity.getResult())) {
//					Resume resumeTmp = null;
//					ImageView defaultResume = null;
//					for (int i = resumes.size() - 1; i >= 0; i--) {
//						resumeTmp = resumes.get(i);
//						defaultResume = (ImageView) mListViews.get(i)
//								.findViewById(R.id.setDefaultResume);
//						if (resumeTmp.getResume_id().equals(
//								resume.getResume_id())) {
//							if ("1".equals(resume.getIsdefaultflag())) {
//								resumeTmp.setIsdefaultflag("0");
//								defaultResume
//										.setBackgroundResource(R.drawable.notselected);
//							} else {
//								resumeTmp.setIsdefaultflag("1");
//								defaultResume
//										.setBackgroundResource(R.drawable.notselected_press);
//							}
//						} else {
//							resumeTmp.setIsdefaultflag("0");
//							defaultResume
//									.setBackgroundResource(R.drawable.notselected);
//						}
//					}
//					resumePagerAdapter.notifyDataSetChanged();
//				}
			} else if (msg.what == REFRESH_BACK) {

			} else if (msg.what == NETWORK_UNUSABLE) {
				HttpUtils.checkNetwork(mActivity, true);
				if (null != resumeMgrListener) {
					resumeMgrListener.onComplete();
				}
			}
		}

	};

	public interface ResumeMgrListener {
		void onComplete();
	}

	public void setResumeMgrListener(ResumeMgrListener l) {
		this.resumeMgrListener = l;
	}

//	private StatusEntity showToast(Message msg) {
//		StatusEntity statusEntity = (StatusEntity) msg.obj;
//		Log.d(TAG, "statusEntity=" + statusEntity);
//		Toast toast = Toast.makeText(mActivity.getParent(),
//				statusEntity.getMessage(), Toast.LENGTH_SHORT);
//		toast.setGravity(Gravity.CENTER, 0, 0);
//		toast.show();
//		return statusEntity;
//	}
}
